<!--订单主表管理-->
<template>
  <div id="businessOrderHeader" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="订单类型">
          <el-select v-model="listQuery.orderType" placeholder="请选择订单类型">
            <el-option label="全部" value="" />
            <el-option label="充值订单" value="0" />
            <el-option label="商品订单" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="listQuery.orderNo" clearable placeholder="请输入订单号" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="交易单号">
          <el-input v-model="listQuery.tradeNo" clearable placeholder="请输入交易单号" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="支付时间">
          <el-date-picker
            v-model="payTimes"
            type="daterange"
            align="right"
            unlink-panels
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
          <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--列表-->
    <div class="table-container flex-main">
      <el-tabs v-model="listQuery.orderStatus" class="common-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="已付款" name="2" />
        <el-tab-pane label="待付款" name="0" />
        <el-tab-pane label="付款失败" name="1" />
        <el-tab-pane label="已关闭" name="3" />
      </el-tabs>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange"
      >
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="订单号/下单时间" prop="id" :show-overflow-tooltip="true" width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.id }}</div>
            <div class="color-default">{{ scope.row.orderDate | formatDate('yyyy-MM-dd hh:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="交易号/支付时间" prop="tradeNo" :show-overflow-tooltip="true" width="240">
          <template slot-scope="scope">
            <div>{{ scope.row.tradeNo }}</div>
            <div class="color-default">{{ scope.row.payTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="订单名称" prop="orderName" min-width="300" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.orderStatus===2" class="color-primary common-cursor" @click="handleLook(scope.row)">{{ scope.row.orderName }}</span>
            <span v-else @click="handleLook(scope.row)">{{ scope.row.orderName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderType" sortable label="订单类型" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.orderType===0" class="color-success">充值订单</span>
            <span v-if="scope.row.orderType===1" class="color-primary">商品订单</span>
          </template>
        </el-table-column>
        <el-table-column prop="grandTotal" sortable label="金额" width="120">
          <template slot-scope="scope"><span class="color-primary">￥{{ scope.row.grandTotal }}</span></template>
        </el-table-column>
        <el-table-column prop="refundTotal" sortable label="退款" width="120">
          <template slot-scope="scope"><span class="color-danger">￥{{ scope.row.refundTotal }}</span></template>
        </el-table-column>
        <el-table-column prop="channelPayWay" label="支付渠道" width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.channelPayWay }}</div>
            <div v-if="scope.row.tradeType" class="color-default">{{ scope.row.tradeType }}</div>
          </template>
        </el-table-column>
        <template v-if="listQuery.orderStatus==='3'">
          <el-table-column :key="Math.random()" label="关闭时间" prop="closedTime" :show-overflow-tooltip="true" width="150">
            <template slot-scope="scope">
              <div class="color-default">{{ scope.row.closedTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</div>
            </template>
          </el-table-column>
        </template>
        <el-table-column prop="userRealName" :show-overflow-tooltip="true" sortable label="姓名/电话" width="100">
          <template slot-scope="scope">
            <div>{{ scope.row.userRealName }}</div>
            <div class="color-default">{{ scope.row.userPhone }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right" fixed="right" width="90">
          <template slot-scope="scope">
            <template v-if="scope.row.orderStatus!==3">
              <template v-if="scope.row.orderStatus===0">
                <button-option type="text" skin="primary" title="发起付款" @click="handleDoPay(scope.row.id)">付款</button-option>
              </template>
              <template v-if="scope.row.orderStatus===2">
                <button-option v-if="scope.row.refundTotal!=scope.row.grandTotal" type="text" skin="danger" title="发起退款" @click="handleDoRefund(scope.row.id)">退款</button-option>
              </template>
              <button-option type="text" skin="primary" title="电子对账" @click="handleReconciliation(scope.row)">对账</button-option>
            </template>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>
    <!--新增/编辑侧边栏-->
    <model-dialog :visible="sideBox.recordShow" :title="sideBox.title" width="900px" @close="sideBox.recordShow = !sideBox.recordShow">
      <template>
        <div class="common-title m-b-20"><h2 class="bold">订单信息</h2></div>
        <div class="businessOrderDetails">
          <el-row class="item" :gutter="10">
            <el-col :span="24">
              订单名称：{{ orderHeader.header.orderName }}
            </el-col>
          </el-row>
          <el-row class="item" :gutter="10">
            <el-col :span="12">
              订单号：{{ orderHeader.header.id }}
            </el-col>
            <el-col :span="12">
              下单时间：{{ orderHeader.header.gmtCreated | formatDate }}
            </el-col>
          </el-row>
          <el-row class="item" :gutter="10">
            <el-col :span="12">
              状态：{{ orderHeader.header.orderStatus === 0 ? '待付款': orderHeader.header.orderStatus===1 ? '付款失败' :'已付款' }}
            </el-col>
            <el-col :span="12">
              支付金额：<span class="color-danger">￥{{ orderHeader.header.grandTotal }}</span>
            </el-col>
          </el-row>
          <el-row class="item" :gutter="10">
            <el-col :span="12">
              姓名：{{ orderHeader.header.userRealName }}
            </el-col>
            <el-col :span="12">
              手机号：{{ orderHeader.header.userPhone }}
            </el-col>
          </el-row>

          <div class="common-title m-b-20"><h2 class="bold">支付信息</h2></div>
          <el-row class="item" :gutter="10">
            <el-col :span="24">
              交易号：{{ orderHeader.payRecord.tradeNo }}
            </el-col>
          </el-row>
          <el-row class="item" :gutter="10">
            <el-col :span="12">
              付款时间：{{ orderHeader.payRecord.gmtCreated | formatDate }}
            </el-col>
            <el-col :span="12">
              状态：{{ orderHeader.payRecord.payStatus === 0 ? '付款成功' :'付款失败' }}
            </el-col>
          </el-row>
          <el-row class="item" :gutter="10">
            <el-col :span="12">
              支付渠道：{{ orderHeader.payRecord.channelPayWay }}
            </el-col>
            <el-col :span="12">
              支付方式：{{ orderHeader.payRecord.tradeType }}
            </el-col>
          </el-row>
          <el-row class="item" :gutter="10">
            <el-col :span="12">
              商户号：{{ orderHeader.payRecord.partnerId }}
            </el-col>
            <el-col :span="12">
              总费用：￥{{ orderHeader.payRecord.totalFee }}
            </el-col>
          </el-row>
          <template v-if="orderHeader.header.orderType===1">
            <div class="common-title m-b-20"><h2 class="bold">购买明细</h2></div>
            <el-table
              :data="orderHeader.headerItems"
              header-cell-class-name="table-header"
              fit
              height="100%"
              highlight-current-row>
              <el-table-column align="center" prop="id" label="#" width="60">
                <template slot-scope="scope">{{ scope.$index+1 }}</template>
              </el-table-column>
              <el-table-column :show-overflow-tooltip="true" label="图片" prop="productImage" width="80" align="center">
                <template slot-scope="scope">
                  <img :src="common.getFileView(scope.row.productImage)" style="width: 46px;height: 46px;" @error="handleImageError">
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="productName" min-width="300" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.productName }}
                  </div>
                  <div>
                    <span class="color-danger">{{ scope.row.productPrice | formatPrice }}</span> * {{ scope.row.productNumber }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </template>
    </model-dialog>
    <pay ref="pay" title="账号充值" @payNotify="handlePayNotify" />
    <model-dialog :visible="recordShow" title="电子对账" @close="recordShow = !recordShow">
      <template>
        <div class="common-title m-b-20"><h2 class="bold">账单信息</h2></div>
        <json-viewer :value="orderJSON" />
      </template>
    </model-dialog>
    <model-dialog :visible="reconciliationShow" title="电子对账" @close="reconciliationShow = !reconciliationShow">
      <template>
        <el-form
          ref="dataForm"
          :rules="businessOrderHeaderRules"
          :model="orderHeaderRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="订单号:">
            <span class="color-danger">￥{{ orderHeaderRecord.id }}</span>
          </el-form-item>
          <el-form-item label="金额总计:">
            <span class="color-danger">￥{{ orderHeaderRecord.grandTotal }}</span>
          </el-form-item>
          <el-form-item label="支付渠道:" prop="channelPayWay">
            <el-radio-group v-model="orderHeaderRecord.channelPayWay" :disabled="orderHeader.header.channelPayWay!=null">
              <el-radio label="wx_v3">微信</el-radio>
              <el-radio label="zfb">支付宝</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
      <template slot="footer">
        <el-button type="primary" @click="doReconciliation">对账</el-button>
      </template>
    </model-dialog>
  </div>
</template>

<script>
import Pay from '@/views/components/pay.vue'
import JsonViewer from 'vue-json-viewer'

export default {
  components: { Pay, JsonViewer },

  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      payTimes: [],
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        orderNo: null,
        tradeNo: null,
        payTimeStart: null,
        payTimeEnd: null,
        orderType: '',
        sort: '-gmtCreated',
        orderStatus: '2'
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        payShow: false,
        title: ''
      },
      orderHeader: {
        header: {},
        payRecord: {},
        headerItems: []
      },
      recordShow: false,
      orderJSON: {},
      reconciliationShow: false,
      orderHeaderRecord: {},
      businessOrderHeaderRules: {
        channelPayWay: [
          { required: true, message: '请选择支付通道', trigger: 'blur' }
        ]
      }

    }
  },
  watch: {
    'sideBox.payShow': function(val) {
      if (val === false) {
        this.$refs.pay.clearInterval()
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleTabClick() {
      this.handleFilter()
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '-gmtCreated'
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        orderType: '',
        orderNo: null,
        tradeNo: null,
        payTimeStart: null,
        payTimeEnd: null,
        sort: this.common.SORT_DEFAULT
      }
      this.payTimes = []
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    async fetchData() {
      if (this.payTimes.length === 2) {
        this.listQuery = {
          ...this.listQuery,
          payTimeStart: this.payTimes[0],
          payTimeEnd: this.payTimes[1]
        }
      }
      const response = await this.$store.dispatch('businessOrderHeaderPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    handleReconciliation(row) {
      this.reconciliationShow = true
      this.orderHeader = {
        header: Object.assign({}, row),
        payRecord: {}
      }
      this.orderHeaderRecord = Object.assign({}, row)
    },
    doReconciliation() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('orderReconciliation', { orderNo: this.orderHeaderRecord.id, channelPayWay: this.orderHeaderRecord.channelPayWay }).then(res => {
            this.$modal.msgSuccess('对账成功')
            this.reconciliationShow = false
            this.recordShow = true
            this.orderJSON = res
            this.fetchData()
          })
        }
      })
    },
    handleDoPay(orderId) {
      this.$nextTick(() => {
        this.$refs.pay.init(orderId)
      })
    },
    handlePayNotify(val) {
      this.handleFilter()
    },
    handleLook(row) {
      this.$store.dispatch('businessOrderHeaderGetDetailsById', row.id).then((res) => {
        this.orderHeader = {
          header: res.orderHeader,
          payRecord: res.paymentRecord,
          headerItems: res.headerItems
        }
        this.sideBox = {
          recordShow: true,
          title: `订单【${row.orderName}】详情`
        }
      }).catch((_) => {})
    },
    handleDoRefund(orderId) {
      this.$store.dispatch('refundPay', {
        orderNo: orderId,
        refundAmount: 0.01,
        refundReason: '我就想退款'
      }).then((res) => {
        this.$modal.msgSuccess('退款申请已发起')
        this.fetchData()
      }).catch((_) => {})
    }

  }
}
</script>
  <style lang="scss" scoped>
   .businessOrderDetails{
      margin-top: 15px;
      .item{
        margin-bottom: 12px;
        font-size: 14px;
        font-weight: 500;
        color: #333;
      }
      .jv-container .jv-code{
        padding: 5px !important;
      }
    }
  </style>

